/** API服务客户端 */
import axios from 'axios'
import type {
  AssessmentResult,
  LearningStyleResult,
  WeaknessAnalysis,
  StudyPlan,
  TrainingSession,
  Question,
  AnswerSubmission,
  ErrorAnalysis,
  ProgressOverview,
  PerformanceMetrics,
  VisualizationData,
  Achievement,
  ErrorAttribution,
  AccuracyPrediction,
  WeeklyGoal,
  ImprovementRecommendation,
  AccuracyStatistics,
  MockExam,
  ExamResult,
  ThinkingAnalysis,
  ThinkingFeedback,
  QuestionStructure,
  ReasoningGuidance,
  TechniqueAnalysis,
  DebateSession,
  DebateEvaluation,
  DebateArgumentResult,
} from '../types'

const API_BASE_URL = (import.meta as any).env?.VITE_API_BASE_URL || 'http://localhost:8000/api/v1'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 15000, // 减少到15秒，避免长时间等待
})

// 为不同类型的API创建专用客户端（不同超时时间）
const quickApiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 5000, // 快速API：5秒超时
})

const slowApiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 60000, // 慢速API（如AI分析）：60秒超时，给大模型充足时间
})

// 为所有客户端设置相同的响应拦截器
const setupInterceptor = (client: typeof apiClient) => {
  client.interceptors.response.use(
    (response) => response.data,
    (error) => {
      // 静默处理超时错误，避免控制台噪音
      if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
        // 超时错误，不输出详细日志
        return Promise.reject(error)
      }
      if (error.response) {
        const status = error.response.status
        if (status >= 500) {
          console.error('API服务器错误:', status)
        }
      }
      return Promise.reject(error)
    }
  )
}

setupInterceptor(apiClient)
setupInterceptor(quickApiClient)
setupInterceptor(slowApiClient)

// 请求拦截器（为所有客户端设置）
const setupRequestInterceptor = (client: typeof apiClient) => {
  client.interceptors.request.use(
    (config) => {
      // Axios 会自动处理 URL 编码，这里只需要确保配置正确
      // 可以在这里添加认证token等
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
}

setupRequestInterceptor(apiClient)
setupRequestInterceptor(quickApiClient)
setupRequestInterceptor(slowApiClient)

/** 评估诊断API */
export const assessmentApi = {
  /** 初始能力评估 */
  initialAssessment: async (data: Record<string, unknown>): Promise<AssessmentResult> => {
    return apiClient.post('/assessment/initial', data)
  },

  /** 学习风格诊断 */
  learningStyleDiagnosis: async (user_id: string): Promise<LearningStyleResult> => {
    return apiClient.post(`/assessment/learning-style?user_id=${user_id}`)
  },

  /** 薄弱环节分析 */
  weaknessAnalysis: async (user_id: string): Promise<WeaknessAnalysis> => {
    return apiClient.get(`/assessment/weaknesses/${user_id}`)
  },

  /** 创建备考计划 */
  createStudyPlan: async (days: number, user_id: string): Promise<StudyPlan> => {
    console.log('📡 [API] 创建学习计划请求:', { days, user_id })
    try {
      const result = await apiClient.post(`/assessment/plan/${days}`, { user_id }) as StudyPlan
      console.log('📡 [API] 创建学习计划响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 创建学习计划失败:', error)
      throw error
    }
  },
}

/** 训练系统API */
export const trainingApi = {
  /** 开始训练会话 */
  startSession: async (user_id: string, plan_id?: string): Promise<TrainingSession> => {
    return apiClient.post('/training/start', { user_id, plan_id })
  },

  /** 获取下一个题目 */
  getNextQuestion: async (session_id: string, question_id?: string): Promise<Question> => {
    const params = question_id ? { question_id } : {}
    return apiClient.get(`/training/question/${session_id}`, { params })
  },

  /** 根据题目ID获取题目 */
  getQuestionById: async (question_id: string): Promise<Question> => {
    return apiClient.get(`/training/question-by-id/${question_id}`)
  },

  /** 提交答案 */
  submitAnswer: async (
    session_id: string,
    question_id: string,
    answer: Record<string, unknown>
  ): Promise<AnswerSubmission> => {
    // 使用slowApiClient，因为可能需要调用大模型进行分析
    return slowApiClient.post('/training/submit', {
      session_id,
      question_id,
      answer,
    })
  },

  /** 错误分析 */
  analyzeError: async (session_id: string, question_id: string): Promise<ErrorAnalysis> => {
    return apiClient.post('/training/analyze-error', {
      session_id,
      question_id,
    })
  },

  /** 获取训练计划 */
  getTrainingPlan: async (plan_id: string): Promise<unknown> => {
    return apiClient.get(`/training/plan/${plan_id}`)
  },

  /** 重置训练会话（清空已做题目记录） */
  resetSession: async (session_id: string): Promise<unknown> => {
    return apiClient.post(`/training/reset-session/${session_id}`)
  },
}

/** 进度追踪API */
export const progressApi = {
  /** 获取进度概览 */
  getOverview: async (user_id: string): Promise<ProgressOverview> => {
    return quickApiClient.get(`/progress/overview/${user_id}`)
  },

  /** 获取性能指标 */
  getPerformanceMetrics: async (
    user_id: string,
    period: string = 'week'
  ): Promise<PerformanceMetrics> => {
    return apiClient.get(`/progress/performance/${user_id}`, { params: { period } })
  },

  /** 获取可视化数据 */
  getVisualizationData: async (user_id: string): Promise<VisualizationData> => {
    return quickApiClient.get(`/progress/visualization/${user_id}`)
  },

  /** 获取成就列表 */
  getAchievements: async (user_id: string): Promise<{ achievements: Achievement[] }> => {
    return quickApiClient.get(`/progress/achievements/${user_id}`)
  },
  
  /** 获取薄弱环节分析 */
  getWeaknessAnalysis: async (user_id: string): Promise<unknown> => {
    return quickApiClient.get(`/progress/weakness/${user_id}`)
  },
}

/** 正确率分析API */
export const analysisApi = {
  /** 错误归因分析 */
  errorAttribution: async (
    user_id: string,
    question_ids: string[]
  ): Promise<ErrorAttribution> => {
    return apiClient.post('/analysis/error-attribution', { user_id, question_ids })
  },

  /** 正确率预测 */
  predictAccuracy: async (
    user_id: string,
    days_ahead: number = 30
  ): Promise<AccuracyPrediction> => {
    return apiClient.get(`/analysis/accuracy-prediction/${user_id}`, {
      params: { days_ahead },
    })
  },

  /** 获取阶段性目标 */
  getWeeklyGoals: async (user_id: string): Promise<{ weekly_goals: WeeklyGoal[] }> => {
    return apiClient.get(`/analysis/weekly-goals/${user_id}`)
  },

  /** 获取提升方案推荐 */
  getRecommendations: async (
    user_id: string,
    error_type?: string
  ): Promise<{ recommendations: ImprovementRecommendation[] }> => {
    return apiClient.post(`/analysis/recommendations/${user_id}`, { error_type })
  },

  /** 获取正确率统计 */
  getStatistics: async (
    user_id: string,
    period: string = 'all'
  ): Promise<AccuracyStatistics> => {
    return apiClient.get(`/analysis/statistics/${user_id}`, { params: { period } })
  },
}

/** 每日学习API */
export const dailyLearningApi = {
  /** 获取每日学习题目 */
  getDailyQuestions: async (
    user_id: string,
    plan_id: string,
    date?: string
  ): Promise<unknown> => {
    console.log('📡 [API] 获取每日题目请求:', { user_id, plan_id, date })
    try {
      const params = date ? { date } : {}
      const result = await apiClient.get(`/daily-learning/${user_id}/${plan_id}`, { params })
      console.log('📡 [API] 获取每日题目响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 获取每日题目失败:', error)
      throw error
    }
  },

  /** 提交每日学习答案 */
  submitDailyAnswer: async (
    user_id: string,
    plan_id: string,
    question_id: string,
    user_answer: string,
    user_notes?: string,
    marked_wrong: boolean = false
  ): Promise<unknown> => {
    // 使用slowApiClient，因为可能需要调用大模型进行分析，需要更长的超时时间
    return slowApiClient.post('/daily-learning/submit', {
      user_id,
      plan_id,
      question_id,
      user_answer,
      user_notes,
      marked_wrong,
    })
  },

  /** 获取错题本 */
  getWrongQuestions: async (user_id: string): Promise<unknown> => {
    return apiClient.get(`/daily-learning/wrong-questions/${user_id}`)
  },

  /** 激活学习计划 */
  activatePlan: async (plan_id: string, user_id: string): Promise<unknown> => {
    console.log('📡 [API] 激活计划请求:', { plan_id, user_id })
    try {
      const result = await apiClient.post(`/daily-learning/activate-plan/${plan_id}`, { user_id })
      console.log('📡 [API] 激活计划响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 激活计划失败:', error)
      throw error
    }
  },

  /** 获取今日学习统计 */
  getTodayStatistics: async (user_id: string, plan_id: string, date?: string): Promise<unknown> => {
    console.log('📡 [API] 获取今日统计请求:', { user_id, plan_id, date })
    try {
      const params = date ? { date } : {}
      const result = await apiClient.get(`/daily-learning/statistics/${user_id}/${plan_id}`, { params })
      console.log('📡 [API] 获取今日统计响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 获取今日统计失败:', error)
      throw error
    }
  },

  /** 继续学习（获取新的训练题目） */
  continueLearning: async (user_id: string, plan_id: string): Promise<unknown> => {
    console.log('📡 [API] 继续学习请求:', { user_id, plan_id })
    try {
      const result = await apiClient.post(`/daily-learning/continue/${user_id}/${plan_id}`)
      console.log('📡 [API] 继续学习响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 继续学习失败:', error)
      throw error
    }
  },
}

/** 用户状态API */
export const userStatusApi = {
  /** 获取用户状态 */
  getUserStatus: async (user_id: string): Promise<unknown> => {
    return apiClient.get(`/user-status/${user_id}`)
  },
  
  /** 获取测试结果 */
  getTestResult: async (user_id: string): Promise<unknown> => {
    console.log('📡 [API] 获取测试结果请求:', { user_id })
    try {
      const result = await apiClient.get(`/user-status/${user_id}/test-result`)
      console.log('📡 [API] 获取测试结果响应:', result)
      return result
    } catch (error) {
      console.error('📡 [API] 获取测试结果失败:', error)
      throw error
    }
  },
}

/** 模拟测试API */
export const mockExamApi = {
  /** 创建模拟测试 */
  createExam: async (user_id: string, exam_type: string = 'quick'): Promise<MockExam> => {
    return apiClient.post('/mock-exam/create', { user_id, exam_type })
  },

  /** 提交模拟测试 */
  submitExam: async (
    exam_id: string,
    user_id: string,
    answers: Record<string, string>,
    time_spent: number
  ): Promise<ExamResult> => {
    // 使用slowApiClient，因为可能需要调用大模型进行分析
    return slowApiClient.post(`/mock-exam/${exam_id}/submit`, {
      user_id,
      answers,
      time_spent,
    })
  },

  /** 获取测试信息 */
  getExamInfo: async (exam_id: string): Promise<unknown> => {
    return apiClient.get(`/mock-exam/${exam_id}`)
  },
}

/** 辩论训练API */
export const debateApi = {
  /** 开始辩论 */
  startDebate: async (
    user_id: string,
    question_id: string,
    question_content: string,
    user_position: string = '中立',
    question_options?: string[]
  ): Promise<DebateSession> => {
    return apiClient.post('/debate/start', {
      user_id,
      question_id,
      question_content,
      user_position,
      question_options: question_options || [],
    })
  },

  /** 提交论点 */
  submitArgument: async (
    debate_id: string,
    user_argument: string,
    round_number?: number
  ): Promise<DebateArgumentResult> => {
    // 使用slowApiClient，因为需要调用大模型生成AI回应
    return slowApiClient.post('/debate/submit-argument', {
      debate_id,
      user_argument,
      round_number,
    })
  },

  /** 获取AI回应（不更新轮次） */
  getAiResponse: async (
    debate_id: string,
    user_argument: string
  ): Promise<any> => {
    // 使用slowApiClient，因为需要调用大模型生成AI回应
    return slowApiClient.post('/debate/ai-response', {
      debate_id,
      user_argument,
    })
  },

  /** 评估辩论 */
  evaluateDebate: async (debate_id: string): Promise<DebateEvaluation> => {
    return apiClient.post('/debate/evaluate', {
      debate_id,
    })
  },

  /** 结束辩论 */
  endDebate: async (debate_id: string): Promise<any> => {
    return apiClient.post('/debate/end', {
      debate_id,
    })
  },

  /** 获取辩论会话 */
  getDebateSession: async (debate_id: string): Promise<DebateSession> => {
    return apiClient.get(`/debate/${debate_id}`)
  },
}

/** 法律思维训练API */
export const legalThinkingApi = {
  /** 分析思维过程 */
  analyzeThinking: async (
    user_id: string,
    question_id: string,
    user_answer: string,
    user_notes: string,
    correct_answer: string,
    question_content: string,
    question_explanation?: string
  ): Promise<ThinkingAnalysis> => {
    return slowApiClient.post('/legal-thinking/analyze', {
      user_id,
      question_id,
      user_answer,
      user_notes,
      correct_answer,
      question_content,
      question_explanation: question_explanation || '',
    })
  },

  /** 提供实时思维反馈 */
  provideFeedback: async (
    user_id: string,
    question_id: string,
    user_thinking: string,
    question_content?: string
  ): Promise<ThinkingFeedback> => {
    return slowApiClient.post('/legal-thinking/feedback', {
      user_id,
      question_id,
      user_thinking,
      question_content,
    })
  },

  /** 分析题目结构 */
  analyzeQuestion: async (
    question_content: string,
    options?: string[]
  ): Promise<QuestionStructure> => {
    return slowApiClient.post('/legal-thinking/analyze-question', {
      question_content,
      options,
    })
  },

  /** 引导推理过程 */
  guideReasoning: async (
    question_content: string,
    user_notes?: string
  ): Promise<ReasoningGuidance> => {
    return slowApiClient.post('/legal-thinking/guide-reasoning', {
      question_content,
      user_notes,
    })
  },

  /** 技巧分析 */
  analyzeTechnique: async (
    question_content: string,
    options: string[]
  ): Promise<TechniqueAnalysis> => {
    return slowApiClient.post('/legal-thinking/technique-analysis', {
      question_content,
      options,
    })
  },

  /** 获取训练计划 */
  getTrainingPlan: async (
    user_id: string,
    period_days: number = 30
  ): Promise<unknown> => {
    return apiClient.get(`/legal-thinking/training-plan/${user_id}`, {
      params: { period_days },
    })
  },
}

export default apiClient

